<?php

namespace fast;

use Exception;

class View
{

    // 模板变量
    public $data = [];

    // 用于静态赋值的模板变量
    protected static $var = [];

    /**
     * 模板变量静态赋值
     * @access public
     * @param mixed $name  变量名
     * @param mixed $value 变量值
     * @return void
     */
    public static function share($name, $value = '')
    {
        if (is_array($name)) {
            self::$var = array_merge(self::$var, $name);
        } else {
            self::$var[$name] = $value;
        }
    }

    /**
     * 模板变量赋值
     * @access public
     * @param mixed $name  变量名
     * @param mixed $value 变量值
     * @return $this
     */
    public function assign($name, $value = '')
    {
        if (is_array($name)) {
            $this->data = array_merge($this->data, $name);
        } else {
            $this->data[$name] = $value;
        }
        return $this;
    }

    /**
     * 模板变量赋值
     * @access public
     * @param string $name  变量名
     * @param mixed  $value 变量值
     */
    public function __set($name, $value)
    {
        $this->data[$name] = $value;
    }

    /**
     * 取得模板显示变量的值
     * @access protected
     * @param string $name 模板变量
     * @return mixed
     */
    public function __get($name)
    {
        return $this->data[$name];
    }

    /**
     * 检测模板变量是否设置
     * @access public
     * @param string $name 模板变量名
     * @return bool
     */
    public function __isset($name)
    {
        return isset($this->data[$name]);
    }

    /**
     * 解析和获取模板内容 用于输出
     * @param string $template 模板文件名或者内容
     * @return string
     * @throws Exception
     */
    public function fetch($template = ''): string
    {
        if (!$template) {
            $track      = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
            $track_file = $track[0]['file'] ?? '';
            if (!$track_file) {
                throw new Exception("追踪不到模板");
            }
            $track_file = str_replace('.php', '', $track_file);
            $track_file = explode(__TYPECHO_THEME_DIR__, $track_file);
            $track_file = explode('/', $track_file[1]);
            $track_file = array_slice($track_file, 2);
            $template   = implode('/', $track_file);
        }

        // 模板变量
        $vars = array_merge(self::$var, $this->data);

        // 页面缓存
        ob_start();
        ob_implicit_flush(0);

        // 渲染输出
        try {
            Compile::instance()->fetch($template, $vars);
        } catch (Exception $e) {
            ob_end_clean();
            throw $e;
        }
        return ob_get_clean();
    }

}